package org.apache.rocketmq.example.transaction;

import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.consumer.ConsumeFromWhere;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.example.MqConstants;

import java.util.List;

/**
 * consumer实例
 *
 * @author qinyupeng
 * @since 2021-08-24 23:35:50
 */
public class TxConsumer {

    public static void main(String[] args) throws InterruptedException, MQClientException {
        // 创建consumer实例
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("tx_consumer_group");
        // 指定名称服务器地址
        consumer.setNamesrvAddr(MqConstants.NameSrvArr);
        // 如果指定的消费者组是一个全新的消费者组，请指定从哪里开始
        consumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_FIRST_OFFSET);
        // 给consumer订阅一个或多个topics，后面参数为正则表达式，用来匹配tag
        consumer.subscribe("txTopic", "*");
        // 注册要在从代理获取的消息到达时执行的回调
        consumer.registerMessageListener(new MessageListenerConcurrently() {
            @Override
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs, ConsumeConcurrentlyContext context) {
                System.out.printf("%s Receive New Messages: %s %n", Thread.currentThread().getName(), msgs);
                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
            }
        });

        // 启动consumer实例
        consumer.start();
        System.out.printf("Consumer Started.%n");
    }
}
